<template>
  <el-table-column
    v-if="columnItem?.children?.length"
    :label="columnItem.label"
    v-bind="columnItem.column"
  >
    <CustomColumn
      v-for="item in columnItem.children"
      :key="item.id"
      :slotNames="slotNames"
      :column-item="item"
      :column-prop="nestColumn(item.prop)"
    >
      <template
        v-for="slotItem in slotNames"
        :key="slotItem"
        #[slotItem]="{ row, index }"
      >
        <slot
          :name="slotItem"
          :index
          :row
        ></slot>
      </template>
    </CustomColumn>
  </el-table-column>
  <el-table-column
    v-else
    :prop="columnItem.prop"
    :label="columnItem.label"
    v-bind="columnItem.column"
  >
    <template #default="{ row, $index }">
      <slot
        v-if="columnItem?.slotName"
        :name="columnItem.slotName"
        :index="$index"
        :row
      ></slot>
      <template v-else>{{ getColumnData(row) }}</template>
    </template>
  </el-table-column>
</template>

<script lang='ts' setup>
import type { tableHeaderType } from '../TableType';

const props = defineProps<{
  slotNames: string[]
  columnItem: tableHeaderType;
  columnProp?: string | undefined;
}>()

defineSlots<{
  [x: string]: (props: { index: number; row: any }) => ({ index: number; row: any })
}>();

/**
 * 多级表头拼接（多级表头时触发此函数）
 * @param propName 绑定的属性名
 */
const nestColumn = (propName: string | undefined) => {
  return props?.columnProp ? props.columnProp + ',' + propName : props?.columnProp
}

/**
 * 解析表头数据（最后一级会触发）
 * @param row 行数据
 */
const getColumnData = (row: any) => {
  if (props?.columnProp) {
    const propNames = props.columnProp.split(',')
    let columnData = row
    propNames.forEach((propName: string) => {
      columnData = columnData?.[propName]
    })
    return columnData
  } else {
    return ""
  }
}
</script>

<style scoped lang='scss'></style>